package com.youlai.boot.system.service.impl;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.sql.Direction;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryMethods;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.youlai.boot.common.constant.RedisConstants;
import com.youlai.boot.common.constant.SystemConstants;
import com.youlai.boot.common.exception.BusinessException;
import com.youlai.boot.common.model.Option;
import com.youlai.boot.core.security.model.UserAuthCredentials;
import com.youlai.boot.core.security.service.PermissionService;
import com.youlai.boot.core.security.token.TokenManager;
import com.youlai.boot.core.security.util.SecurityUtils;
import com.youlai.boot.shared.mail.service.MailService;
import com.youlai.boot.shared.sms.enums.SmsTypeEnum;
import com.youlai.boot.shared.sms.service.SmsService;
import com.youlai.boot.system.converter.UserConverter;
import com.youlai.boot.system.mapper.UserMapper;
import com.youlai.boot.system.model.bo.UserBO;
import com.youlai.boot.system.model.dto.UserExportDTO;
import com.youlai.boot.system.model.entity.SysDeptEntity;
import com.youlai.boot.system.model.entity.SysRoleEntity;
import com.youlai.boot.system.model.entity.SysUserEntity;
import com.youlai.boot.system.model.entity.SysUserRoleEntity;
import com.youlai.boot.system.model.form.*;
import com.youlai.boot.system.model.query.UserPageQuery;
import com.youlai.boot.system.model.vo.UserInfoVO;
import com.youlai.boot.system.model.vo.UserPageVO;
import com.youlai.boot.system.model.vo.UserProfileVO;
import com.youlai.boot.system.service.RoleMenuService;
import com.youlai.boot.system.service.RoleService;
import com.youlai.boot.system.service.UserRoleService;
import com.youlai.boot.system.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户业务实现类
 *
 * @author haoxr
 * @since 2022/1/14
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUserEntity> implements UserService {

    private final PasswordEncoder passwordEncoder;

    private final UserRoleService userRoleService;

    private final RoleMenuService roleMenuService;

    private final RoleService roleService;

    private final PermissionService permissionService;

    private final SmsService smsService;

    private final MailService mailService;

    private final StringRedisTemplate redisTemplate;

    private final TokenManager tokenManager;

    private final UserConverter userConverter;

    /**
     * 获取用户分页列表
     *
     * @param queryParams 查询参数
     * @return {@link Page<UserPageVO>} 用户分页列表
     */
    @Override
    public Page<UserPageVO> getUserPage(UserPageQuery queryParams) {

        // 参数构建
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        Page<UserBO> page = new Page<>(pageNum, pageSize);
        // 查询数据
        QueryWrapper query = QueryWrapper.create().from(SysUserEntity.class)
                .select(
                        QueryMethods.column(SysUserEntity::getId).as(UserBO::getId),
                        QueryMethods.column(SysUserEntity::getUsername).as(UserBO::getUsername),
                        QueryMethods.column(SysUserEntity::getEmail).as(UserBO::getEmail),
                        QueryMethods.column(SysUserEntity::getNickname).as(UserBO::getNickname),
                        QueryMethods.column(SysUserEntity::getMobile).as(UserBO::getMobile),
                        QueryMethods.column(SysUserEntity::getGender).as(UserBO::getGender),
                        QueryMethods.column(SysUserEntity::getAvatar).as(UserBO::getAvatar),
                        QueryMethods.column(SysUserEntity::getStatus).as(UserBO::getStatus),
                        QueryMethods.column(SysUserEntity::getCreateTime).as(UserBO::getCreateTime),
                        QueryMethods.column(SysDeptEntity::getName).as(UserBO::getDeptName),
                        QueryMethods.groupConcat(QueryMethods.column(SysRoleEntity::getName)).as(UserBO::getRoleNames)
                )
                .leftJoin(SysDeptEntity.class).on(q -> q.and(SysDeptEntity::getId).eq(SysUserEntity::getDeptId))
                .leftJoin(SysUserRoleEntity.class).on(q -> q.and(SysUserRoleEntity::getUserId).eq(SysUserEntity::getId)
                        .and(SysUserRoleEntity::getRoleId).in(queryParams.getRoleIds(), queryParams.getRoleIds() != null && !queryParams.getRoleIds().isEmpty()))
                .leftJoin(SysRoleEntity.class).on(q -> q.and(SysRoleEntity::getId).eq(SysUserRoleEntity::getRoleId))
                .and(SysUserEntity::getStatus).eq(queryParams.getStatus(), queryParams.getStatus() != null);

        if (queryParams.getDeptId() != null) {
            query.and("concat(',',concat(sys_dept.tree_path,',',sys_dept.id),',') like concat('%,',?,',%')", queryParams.getDeptId());
        }

        query.and(q -> q.and(SysUserEntity::getUsername).like(queryParams.getKeywords())
                        .or(SysUserEntity::getNickname).like(queryParams.getKeywords())
                        .or(SysUserEntity::getMobile).like(queryParams.getKeywords()),
                StrUtil.isNotBlank(queryParams.getKeywords()));

        if (queryParams.getCreateTime() != null) {
            String startDate = queryParams.getCreateTime().get(0);
            String endDate = queryParams.getCreateTime().get(1);

            if (StrUtil.isNotBlank(startDate) && StrUtil.isNotBlank(endDate)) {
                query.and(SysUserEntity::getCreateTime).between(startDate, endDate);
            }

            if (StrUtil.isNotBlank(startDate)) {
                query.and(SysUserEntity::getCreateTime).ge(startDate);
            }

            if (StrUtil.isNotBlank(endDate)) {
                query.and(SysUserEntity::getCreateTime).le(endDate);
            }
        }

        query.groupBy(SysUserEntity::getId);

        if (StrUtil.isNotBlank(queryParams.getField()) && queryParams.getDirection() != null) {
            if (queryParams.getDirection().equals(Direction.ASC)) {
                query.orderBy(queryParams.getField() + "asc");
            }

            if (queryParams.getDirection().equals(Direction.DESC)) {
                query.orderBy(queryParams.getField() + "desc");
            }

        } else {
            query.orderBy(SysUserEntity::getUpdateTime).desc()
                    .orderBy(SysUserEntity::getCreateTime).desc();
        }

        query.orderBy(SysUserEntity::getId).desc();

        Page<UserBO> userPage = this.pageAs(page, query, UserBO.class);

        // 实体转换
        return userConverter.toPageVo(userPage);
    }

    /**
     * 获取用户表单数据
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public UserForm getUserFormData(Long userId) {
        return this.mapper.selectOneWithRelationsByQueryAs(
                QueryWrapper.create().from(SysUserEntity.class)
                        .and(SysUserEntity::getId).eq(userId),
                UserForm.class
        );
    }

    /**
     * 新增用户
     *
     * @param userForm 用户表单对象
     * @return
     */
    @Override
    public boolean saveUser(UserForm userForm) {

        String username = userForm.getUsername();

        long count = this.count(QueryWrapper.create().eq(SysUserEntity::getUsername, username));
        Assert.isTrue(count == 0, "用户名已存在");

        // 实体转换 form->entity
        SysUserEntity entity = userConverter.toEntity(userForm);

        // 设置默认加密密码
        String defaultEncryptPwd = passwordEncoder.encode(SystemConstants.DEFAULT_PASSWORD);
        entity.setPassword(defaultEncryptPwd);

        // 新增用户
        boolean result = this.save(entity);

        if (result) {
            // 保存用户角色
            userRoleService.saveUserRoles(entity.getId(), userForm.getRoleIds());
        }
        return result;
    }

    /**
     * 更新用户
     *
     * @param userId   用户ID
     * @param userForm 用户表单对象
     * @return
     */
    @Override
    @Transactional
    public boolean updateUser(Long userId, UserForm userForm) {

        String username = userForm.getUsername();

        long count = this.count(QueryWrapper.create()
                .eq(SysUserEntity::getUsername, username)
                .ne(SysUserEntity::getId, userId)
        );
        Assert.isTrue(count == 0, "用户名已存在");

        // form -> entity
        SysUserEntity entity = userConverter.toEntity(userForm);

        // 修改用户
        boolean result = this.updateById(entity);

        if (result) {
            // 保存用户角色
            userRoleService.saveUserRoles(entity.getId(), userForm.getRoleIds());
        }
        return result;
    }

    /**
     * 删除用户
     *
     * @param idsStr 用户ID，多个以英文逗号(,)分割
     * @return true|false
     */
    @Override
    public boolean deleteUsers(String idsStr) {
        Assert.isTrue(StrUtil.isNotBlank(idsStr), "删除的用户数据为空");
        // 逻辑删除
        List<Long> ids = Arrays.stream(idsStr.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        return this.removeByIds(ids);

    }

    /**
     * 根据用户名获取认证信息
     *
     * @param username 用户名
     * @return 用户认证信息 {@link UserAuthCredentials}
     */
    @Override
    public UserAuthCredentials getAuthCredentialsByUsername(String username) {
        UserAuthCredentials userAuthCredentials = this.mapper.selectOneWithRelationsByQueryAs(
                QueryWrapper.create().from(SysUserEntity.class)
                        .select(QueryMethods.column(SysUserEntity::getId).as(UserAuthCredentials::getUserId))
                        .select(QueryMethods.column(SysUserEntity::getUsername).as(UserAuthCredentials::getUsername))
                        .select(QueryMethods.column(SysUserEntity::getNickname).as(UserAuthCredentials::getNickname))
                        .select(QueryMethods.column(SysUserEntity::getPassword).as(UserAuthCredentials::getPassword))
                        .select(QueryMethods.column(SysUserEntity::getStatus).as(UserAuthCredentials::getStatus))
                        .select(QueryMethods.column(SysUserEntity::getDeptId).as(UserAuthCredentials::getDeptId))
                        .and(SysUserEntity::getUsername).eq(username),
                UserAuthCredentials.class
        );
        if (userAuthCredentials != null) {
            Set<String> roles = CollStreamUtil.toSet(userAuthCredentials.getRoles(), SysRoleEntity::getCode);
            // 获取最大范围的数据权限
            Integer dataScope = roleService.getMaximumDataScope(roles);
            userAuthCredentials.setDataScope(dataScope);
        }
        return userAuthCredentials;
    }


    /**
     * 根据 openid 获取用户认证信息
     *
     * @param openid 微信 OpenId
     * @return {@link UserAuthCredentials}
     */
    @Override
    public UserAuthCredentials getAuthCredentialsByOpenId(String openid) {
        UserAuthCredentials userAuthCredentials = this.mapper.selectOneWithRelationsByQueryAs(
                QueryWrapper.create().from(SysUserEntity.class)
                        .select(QueryMethods.column(SysUserEntity::getId).as(UserAuthCredentials::getUserId))
                        .select(QueryMethods.column(SysUserEntity::getUsername).as(UserAuthCredentials::getUsername))
                        .select(QueryMethods.column(SysUserEntity::getNickname).as(UserAuthCredentials::getNickname))
                        .select(QueryMethods.column(SysUserEntity::getPassword).as(UserAuthCredentials::getPassword))
                        .select(QueryMethods.column(SysUserEntity::getStatus).as(UserAuthCredentials::getStatus))
                        .select(QueryMethods.column(SysUserEntity::getDeptId).as(UserAuthCredentials::getDeptId))
                        .and(SysUserEntity::getOpenid).eq(openid),
                UserAuthCredentials.class
        );
        if (userAuthCredentials != null) {
            Set<String> roles = CollStreamUtil.toSet(userAuthCredentials.getRoles(), SysRoleEntity::getCode);
            // 获取最大范围的数据权限
            Integer dataScope = roleService.getMaximumDataScope(roles);
            userAuthCredentials.setDataScope(dataScope);
        }
        return userAuthCredentials;
    }

    /**
     * 根据微信 OpenID 注册或绑定用户
     * <p>
     * TODO 根据手机号绑定用户
     *
     * @param openId 微信 OpenID
     */
    @Override
    public void registerOrBindWechatUser(String openId) {
        SysUserEntity user = this.getOne(
                QueryWrapper.create().eq(SysUserEntity::getOpenid, openId)
        );
        if (user == null) {
            user = new SysUserEntity()
                    .setNickname("微信用户")// 默认昵称
                    .setUsername(openId)  // TODO 后续替换为手机号
                    .setOpenid(openId)
                    .setGender(0) // 保密
                    .setUpdatedBy(SecurityUtils.getUserId())
                    .setPassword(SystemConstants.DEFAULT_PASSWORD);

            this.save(user);
            // 为了默认系统管理员角色，这里按需调整，实际情况绑定已存在的系统用户，另一种情况是给默认游客角色，然后由系统管理员设置用户的角色
            SysUserRoleEntity userRole = new SysUserRoleEntity().setUserId(user.getId()).setRoleId(1L); // TODO 系统管理员
            userRoleService.save(userRole);
        }
    }

    /**
     * 根据手机号获取用户认证信息
     *
     * @param mobile 手机号
     * @return {@link UserAuthCredentials}
     */
    @Override
    public UserAuthCredentials getAuthCredentialsByMobile(String mobile) {
        UserAuthCredentials userAuthCredentials = this.mapper.selectOneWithRelationsByQueryAs(
                QueryWrapper.create().from(SysUserEntity.class)
                        .select(QueryMethods.column(SysUserEntity::getId).as(UserAuthCredentials::getUserId))
                        .select(QueryMethods.column(SysUserEntity::getUsername).as(UserAuthCredentials::getUsername))
                        .select(QueryMethods.column(SysUserEntity::getNickname).as(UserAuthCredentials::getNickname))
                        .select(QueryMethods.column(SysUserEntity::getPassword).as(UserAuthCredentials::getPassword))
                        .select(QueryMethods.column(SysUserEntity::getStatus).as(UserAuthCredentials::getStatus))
                        .select(QueryMethods.column(SysUserEntity::getDeptId).as(UserAuthCredentials::getDeptId))
                        .and(SysUserEntity::getMobile).eq(mobile),
                UserAuthCredentials.class
        );
        if (userAuthCredentials != null) {
            Set<String> roles = CollStreamUtil.toSet(userAuthCredentials.getRoles(), SysRoleEntity::getCode);
            // 获取最大范围的数据权限
            Integer dataScope = roleService.getMaximumDataScope(roles);
            userAuthCredentials.setDataScope(dataScope);
        }
        return userAuthCredentials;
    }

    /**
     * 获取导出用户列表
     *
     * @param queryParams 查询参数
     * @return {@link List<UserExportDTO>} 导出用户列表
     */
    @Override
    public List<UserExportDTO> listExportUsers(UserPageQuery queryParams) {

        QueryWrapper query = QueryWrapper.create().from(SysUserEntity.class)
                .select(
                        QueryMethods.column(SysUserEntity::getId),
                        QueryMethods.column(SysUserEntity::getUsername),
                        QueryMethods.column(SysUserEntity::getNickname),
                        QueryMethods.column(SysUserEntity::getMobile),
                        QueryMethods.case_(QueryMethods.column(SysUserEntity::getGender))
                                .when(1).then("男")
                                .when(2).then("女")
                                .else_("保密").end().as(UserExportDTO::getGender),
                        QueryMethods.column(SysDeptEntity::getName).as(UserExportDTO::getDeptName),
                        QueryMethods.column(SysUserEntity::getCreateTime)
                )
                .leftJoin(SysDeptEntity.class).on(q -> q.and(SysUserEntity::getDeptId).eq(SysDeptEntity::getId))
                .where(SysUserEntity::getUsername).ne("root")
                .and(q -> q.and(SysUserEntity::getUsername).like(queryParams.getKeywords())
                                .or(SysUserEntity::getNickname).like(queryParams.getKeywords())
                                .or(SysUserEntity::getMobile).like(queryParams.getKeywords()),
                        StrUtil.isNotBlank(queryParams.getKeywords()))
                .and(SysUserEntity::getStatus).eq(queryParams.getStatus(), queryParams.getStatus() != null);

        if (queryParams.getDeptId() != null) {
            query.and("concat(',',concat(sys_dept.tree_path,',',sys_dept.id),',') like concat('%,',?,',%')", queryParams.getDeptId());
        }
        query.groupBy(SysUserEntity::getId);


        return this.listAs(
                query,
                UserExportDTO.class
        );
    }

    /**
     * 获取登录用户信息
     *
     * @return {@link UserInfoVO}   用户信息
     */
    @Override
    public UserInfoVO getCurrentUserInfo() {

        String username = SecurityUtils.getUsername();

        // 获取登录用户基础信息
        SysUserEntity user = this.getOne(QueryWrapper.create()
                .select(SysUserEntity::getId, SysUserEntity::getUsername, SysUserEntity::getNickname, SysUserEntity::getAvatar)
                .eq(SysUserEntity::getUsername, username)

        );

        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // entity->VO
        UserInfoVO userInfoVO = userConverter.toUserInfoVo(user);

        // 用户角色集合
        Set<String> roles = SecurityUtils.getRoles();
        userInfoVO.setRoles(roles);

        // 用户权限集合
        if (CollectionUtil.isNotEmpty(roles)) {
            Set<String> perms = permissionService.getRolePermsFormCache(roles);
            userInfoVO.setPerms(perms);
        }
        return userInfoVO;
    }

    /**
     * 获取个人中心用户信息
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public UserProfileVO getUserProfile(Long userId) {
        return this.getOneAs(
                QueryWrapper.create().from(SysUserEntity.class)
                        .select(
                                QueryMethods.column(SysUserEntity::getId).as(UserBO::getId),
                                QueryMethods.column(SysUserEntity::getUsername).as(UserBO::getUsername),
                                QueryMethods.column(SysUserEntity::getEmail).as(UserBO::getEmail),
                                QueryMethods.column(SysUserEntity::getNickname).as(UserBO::getNickname),
                                QueryMethods.column(SysUserEntity::getMobile).as(UserBO::getMobile),
                                QueryMethods.column(SysUserEntity::getGender).as(UserBO::getGender),
                                QueryMethods.column(SysUserEntity::getAvatar).as(UserBO::getAvatar),
                                QueryMethods.column(SysUserEntity::getStatus).as(UserBO::getStatus),
                                QueryMethods.column(SysUserEntity::getCreateTime).as(UserBO::getCreateTime),
                                QueryMethods.column(SysDeptEntity::getName).as(UserBO::getDeptName),
                                QueryMethods.groupConcat(QueryMethods.column(SysRoleEntity::getName)).as(UserBO::getRoleNames)
                        )
                        .leftJoin(SysDeptEntity.class).on(q -> q.and(SysDeptEntity::getId).eq(SysUserEntity::getDeptId))
                        .leftJoin(SysUserRoleEntity.class).on(q -> q.and(SysUserRoleEntity::getUserId).eq(SysUserEntity::getId))
                        .leftJoin(SysRoleEntity.class).on(q -> q.and(SysRoleEntity::getId).eq(SysUserRoleEntity::getRoleId))
                        .where(SysUserEntity::getId).eq(userId),
                UserProfileVO.class
        );
    }

    /**
     * 修改个人中心用户信息
     *
     * @param formData 表单数据
     * @return
     */
    @Override
    public boolean updateUserProfile(UserProfileForm formData) {
        Long userId = SecurityUtils.getUserId();
        SysUserEntity entity = userConverter.toEntity(formData);
        entity.setId(userId);
        return this.updateById(entity);
    }


    /**
     * 修改用户密码
     *
     * @param userId 用户ID
     * @param data   密码修改表单数据
     * @return
     */
    @Override
    public boolean changePassword(Long userId, PasswordUpdateForm data) {

        SysUserEntity user = this.getById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        String oldPassword = data.getOldPassword();

        // 校验原密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new BusinessException("原密码错误");
        }
        // 新旧密码不能相同
        if (passwordEncoder.matches(data.getNewPassword(), user.getPassword())) {
            throw new BusinessException("新密码不能与原密码相同");
        }

        String newPassword = data.getNewPassword();
        boolean result = this.update(
                new SysUserEntity().setPassword(passwordEncoder.encode(newPassword)),
                QueryWrapper.create().eq(SysUserEntity::getId, userId)
        );

        if (result) {
            // 加入黑名单，重新登录
            String accessToken = SecurityUtils.getTokenFromRequest();
            tokenManager.invalidateToken(accessToken);
        }
        return result;
    }

    /**
     * 重置密码
     *
     * @param userId   用户ID
     * @param password 密码重置表单数据
     * @return
     */
    @Override
    public boolean resetPassword(Long userId, String password) {
        return this.update(
                new SysUserEntity().setPassword(passwordEncoder.encode(password)),
                QueryWrapper.create().eq(SysUserEntity::getId, userId)
        );
    }

    /**
     * 发送短信验证码(绑定或更换手机号)
     *
     * @param mobile 手机号
     * @return true|false
     */
    @Override
    public boolean sendMobileCode(String mobile) {

        // String code = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        // TODO 为了方便测试，验证码固定为 1234，实际开发中在配置了厂商短信服务后，可以使用上面的随机验证码
        String code = "1234";

        Map<String, String> templateParams = new HashMap<>();
        templateParams.put("code", code);
        boolean result = smsService.sendSms(mobile, SmsTypeEnum.CHANGE_MOBILE, templateParams);
        if (result) {
            // 缓存验证码，5分钟有效，用于更换手机号校验
            String redisCacheKey = StrUtil.format(RedisConstants.Captcha.MOBILE_CODE, mobile);
            redisTemplate.opsForValue().set(redisCacheKey, code, 5, TimeUnit.MINUTES);
        }
        return result;
    }

    /**
     * 绑定或更换手机号
     *
     * @param form 表单数据
     * @return true|false
     */
    @Override
    public boolean bindOrChangeMobile(MobileUpdateForm form) {

        Long currentUserId = SecurityUtils.getUserId();
        SysUserEntity currentUser = this.getById(currentUserId);

        if (currentUser == null) {
            throw new BusinessException("用户不存在");
        }

        // 校验验证码
        String inputVerifyCode = form.getCode();
        String mobile = form.getMobile();

        String cacheKey = StrUtil.format(RedisConstants.Captcha.MOBILE_CODE, mobile);

        String cachedVerifyCode = redisTemplate.opsForValue().get(cacheKey);

        if (StrUtil.isBlank(cachedVerifyCode)) {
            throw new BusinessException("验证码已过期");
        }
        if (!inputVerifyCode.equals(cachedVerifyCode)) {
            throw new BusinessException("验证码错误");
        }
        // 验证完成删除验证码
        redisTemplate.delete(cacheKey);
        
        // 更新手机号码
        return this.update(
                new SysUserEntity().setMobile(mobile),
                QueryWrapper.create().eq(SysUserEntity::getId, currentUserId)
        );
        
    }

    /**
     * 发送邮箱验证码（绑定或更换邮箱）
     *
     * @param email 邮箱
     */
    @Override
    public void sendEmailCode(String email) {

        // String code = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        // TODO 为了方便测试，验证码固定为 1234，实际开发中在配置了邮箱服务后，可以使用上面的随机验证码
        String code = "1234";

        mailService.sendMail(email, "邮箱验证码", "您的验证码为：" + code + "，请在5分钟内使用");
        // 缓存验证码，5分钟有效，用于更换邮箱校验
        String redisCacheKey = StrUtil.format(RedisConstants.Captcha.EMAIL_CODE, email);
        redisTemplate.opsForValue().set(redisCacheKey, code, 5, TimeUnit.MINUTES);
    }

    /**
     * 修改当前用户邮箱
     *
     * @param form 表单数据
     * @return true|false
     */
    @Override
    public boolean bindOrChangeEmail(EmailUpdateForm form) {

        Long currentUserId = SecurityUtils.getUserId();

        SysUserEntity currentUser = this.getById(currentUserId);
        if (currentUser == null) {
            throw new BusinessException("用户不存在");
        }

        // 获取前端输入的验证码
        String inputVerifyCode = form.getCode();

        // 获取缓存的验证码
        String email = form.getEmail();
        String redisCacheKey = RedisConstants.Captcha.EMAIL_CODE + email;
        String cachedVerifyCode = redisTemplate.opsForValue().get(redisCacheKey);

        if (StrUtil.isBlank(cachedVerifyCode)) {
            throw new BusinessException("验证码已过期");
        }

        if (!inputVerifyCode.equals(cachedVerifyCode)) {
            throw new BusinessException("验证码错误");
        }
        // 验证完成删除验证码
        redisTemplate.delete(redisCacheKey);

        // 更新邮箱地址
        return this.update(
                new SysUserEntity().setEmail(email),
                QueryWrapper.create().eq(SysUserEntity::getId, currentUserId)
        );
    }

    /**
     * 获取用户选项列表
     *
     * @return {@link List<Option<String>>} 用户选项列表
     */
    @Override
    public List<Option<String>> listUserOptions() {
        List<SysUserEntity> list = this.list();
        if (CollectionUtil.isNotEmpty(list)) {
            return list.stream().map(user -> new Option<>(user.getId().toString(), user.getNickname())).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

}
